import os

import cv2
import numpy as np

orignal_path = 'I:\\黄帝内经加工版本\\34-38分'
orignalNew_path = 'I:\\黄帝内经加工版本\\34-38白'
if not os.path.isdir(orignalNew_path):
    os.makedirs(orignalNew_path)
for ind, file in enumerate(os.listdir(orignal_path)):
    filePath = os.path.join(orignal_path, file)
    img = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), -1)
    img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret,dts = cv2.threshold(img2,158,255,cv2.THRESH_BINARY)

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(2,2))

    #dst2 = cv2.dilate(dts,kernel=kernel,iterations=1)
    dst2 = cv2.erode(dts, kernel, iterations=1)

    filePathNew = os.path.join(orignalNew_path, file)
    #cv2.imwrite(filePathNew, dts)
    cv2.imencode('.jpg', dst2)[1].tofile(filePathNew)
# 二值化古籍黑白化
#ret,dts = cv2.threshold(img2,0,255,cv2.THRESH_BINARY + cv2.THRESH_OTSU) #自动设置颜色范围
#cv2.imwrite('m2.jpg', dts)
cv2.waitKey(0)